package script.groovy

import cn.hutool.core.collection.CollectionUtil
import cn.net.sinodata.system.msghandler.parse.scripthandler.CommonScriptResult
import org.dom4j.Element

/**
 * 获取交易员信息
 * @param jsonResult
 * @return
 */
CommonScriptResult execute(Element parseResult) {
    Map<String, Object> dataMap = new HashMap<>();

    // 获取side
    Element sideElement = (Element)parseResult.selectSingleNode("/message/body/Side");
    if (sideElement == null || !sideElement.hasContent()) {
        return CommonScriptResult.empty("Side节点值为空")
    }
    String side = sideElement.getText();

    // 获取NoPartyIDs
    List<Element> noPartyIDsRepeatGroup = (List<Element>)parseResult.selectNodes("/message/body/NoPartyIDs");
    if (CollectionUtil.isEmpty(noPartyIDsRepeatGroup) || noPartyIDsRepeatGroup.size() == 0) {
        return CommonScriptResult.empty("NoPartyIDs节点为空")
    }
    Element noPartyIDsElement = noPartyIDsRepeatGroup.get(1);
    List<Element> partyRoleElements = noPartyIDsElement.elements("PartyRole");
    List<Element> noPartySubIDsRepeatGroup = noPartyIDsElement.elements("NoPartySubIDs");

    for (int i=0; i<partyRoleElements.size(); i++) {
        String partyRole = partyRoleElements.get(i).getText();
        Element noPartySubIDsElement = noPartySubIDsRepeatGroup.get(i*2+1);
        List<Element>  partySubIDElements = noPartySubIDsElement.elements("PartySubID");
        List<Element>  partySubIDTypeElements = noPartySubIDsElement.elements("PartySubIDType");

        int size = partySubIDTypeElements.size()
        if ((side == "1" && partyRole == "119") || (side == "4" && partyRole == "120")) { // 本方交易员相关信息
            Map<String, String> ourMap = new HashMap<>()
            // 遍历PartySubID和PartySubIDType
            for (int j=0; j<size; j++) {
                String idType = partySubIDTypeElements.get(j).getText()
                String id = partySubIDElements.get(j).getText()
                ourMap.put(idType, id);
            }
            dataMap.put("our", ourMap);
        } else if ((side == "1" && partyRole == "120") || (side == "4" && partyRole == "119")) { //对手方交易员相关信息
            Map<String, String> counterpartyMap = new HashMap<>()
            // 遍历PartySubID和PartySubIDType
            for (int j=0; j<size; j++) {
                String idType = partySubIDTypeElements.get(j).getText()
                String id = partySubIDElements.get(j).getText()
                counterpartyMap.put(idType, id);
            }
            dataMap.put("counterparty", counterpartyMap);
        }
    }
    return CommonScriptResult.success(dataMap);
}

